<template>
  <el-dialog
    v-model="dialogVisible"
    v-if="load"
    title="生成采购单"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    width="1070"
    :before-close="close"
    :z-index="2000"
  >
    <div class="sampleTitle">产品信息</div>
    <el-table ref="tableRef" :data="form.sku" border style="width: 100%">
      <el-table-column label="产品图片" width="100">
        <template #default="{ row }">
          <img style="width: 52px; height: 52px" :src="row.attr_img" />
        </template>
      </el-table-column>
      <el-table-column label="SKU" width="100">
        <template #default="{ row }">
          <span>{{ row.goods_sku }}</span>
        </template>
      </el-table-column>
      <el-table-column label="产品名称">
        <template #default="{ row }">
          <div class="overflow-line2">{{ row.sku_cn_title }}</div>
        </template>
      </el-table-column>
      <el-table-column label="采购数量" width="95">
        <template #header>采购数量<span class="text-[#f56c6c] ml-1">*</span></template>
        <template #default="{ row }">
          <el-input
            type="text"
            v-model="row.purchase_quantity"
            placeholder="请输入"
            oninput="value=value.replace(/[^\d]/g,'')"
          ></el-input>
        </template>
      </el-table-column>
      <el-table-column label="单个SKU运费" width="120">
        <template #default="{ row }">
          <el-input
            type="text"
            v-model="row.tracking_price"
            placeholder="请输入"
            oninput="value=value.replace(/[^\d.]/g,'').replace(/^(\d*\.?\d{0,6}).*/,'$1')"
            @blur="trackingChange(row)"
          ></el-input>
        </template>
      </el-table-column>
      <el-table-column label="采购单价" width="95">
        <template #header>采购单价<span class="text-[#f56c6c] ml-1">*</span></template>
        <template #default="{ row }">
          <!-- <el-input
            type="text"
            v-model="row.purchase_price"
            placeholder="请输入"
            oninput="value=value.replace(/[^\d.]/g,'').replace(/^(\d*\.?\d{0,2}).*/,'$1')"
          ></el-input> -->
          {{ row.purchase_price }}
        </template>
      </el-table-column>
      <el-table-column label="供应商报价" width="180">
        <template #default="{ row }">
          <div>
            采购未税报价：<dataAuthority
              auth="unit_price"
              :value="row.unit_price"
            ></dataAuthority>
          </div>
          <div>
            采购含税价：<dataAuthority
              auth="unit_price_tax"
              :value="row.unit_price_tax"
            ></dataAuthority>
          </div>
          <div>
            采购未税价：<dataAuthority
              auth="purchase_untaxed_price"
              :value="row.purchase_untaxed_price"
            ></dataAuthority>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="预计到货时间" width="170">
        <template #header
          >预计到货时间<span class="text-[#f56c6c] ml-1">*</span></template
        >
        <template #default="{ row }">
          <el-date-picker
            style="width: 140px"
            v-model="row.expect_delivery_time"
            value-format="YYYY-MM-DD"
            type="date"
            placeholder="选择日期"
          />
        </template>
      </el-table-column>
    </el-table>
    <div class="sampleTitle">样品单信息</div>
    <el-form
      ref="formRef"
      :model="form"
      label-align="right"
      label-width="90"
      size="default"
      label-position="top"
    >
      <el-row :gutter="21">
        <el-col :span="8">
          <el-form-item label="供应商名称" required>
            <el-input v-model="form.basic.supplier_name" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="供应商类型">
            <el-select
              class="w-full"
              v-model="form.basic.purchase_type"
              placeholder="供应商类型"
            >
              <el-option
                v-for="item in options.purchase_type"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="采购人员" required>
            <select-personnel
              class="w-full"
              v-model="form.basic.purchaser_id"
            ></select-personnel>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="目的仓库" required>
            <SelectFilterWarehouse
              class="w-full"
              v-model="form.basic.destination_warehouse"
            ></SelectFilterWarehouse>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="总运费">
            <vGroup class="w-full">
              <el-input
                v-model="form.basic.tracking_price"
                placeholder="总运费"
              ></el-input>
              <el-button type="primary" @click="updateTracking">分摊</el-button>
            </vGroup>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="采购备注">
            <el-input
              v-model="form.basic.remark"
              type="textarea"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="close">取消</el-button>
      <el-button type="primary" @click="save">生成采购单</el-button>
      <el-checkbox
        v-model="form.basic.is_notice"
        :true-label="1"
        :false-label="0"
        class="ml-4"
        size="large"
      >
        消息通知采购人员
      </el-checkbox>
    </template>
  </el-dialog>
</template>
<script setup>
import { ref, reactive, nextTick, toRefs } from "vue";
import SelectFilterWarehouse from "@/components/SelectFilterWarehouse";
import SelectCurrency from "@/components/SelectCurrency";
import { getBaseOptions } from "@/api/index.js";
import XEUtils from "xe-utils";
import { createPurchaseOrder, getPurchaseDetail } from "../api/index.js";
import { ElMessage } from "element-plus";

const data = reactive({
  dialogVisible: false,
  form: {
    basic: {
      prepare_type: 1,
      supplier_id: "",
      destination_warehouse: "",
      supplier: [],
    },
    sku: [],
  },
  load: false,
});

const { dialogVisible, form, load } = toRefs(data);

const open = async (ids) => {
  if (!load.value) {
    load.value = true;
    await 1;
  }
  dialogVisible.value = true;
  initForm();
  getDetail(ids);
};

const initForm = () => {
  form.value = {
    basic: {
      prepare_type: 1,
      supplier_id: "",
      currency: 35,
      destination_warehouse: "",
      supplier: [],
    },
    sku: [],
  };
};

const getDetail = async (id) => {
  try {
    const res = await getPurchaseDetail({ id });
    res.data.sku.forEach((i) => {
      i.sku = i.goods_sku;
    });
    form.value = res.data;

    form.value.basic.sample_order_num = res.data.sku.map((i) => {
      return i.sample_order_num;
    });
    form.value.basic.currency = 35;
    form.value.basic.is_notice = 0;
    form.value.basic.remark = form.value.basic.procurement_remarks;
    form.value.basic.tracking_price = res.data.basic.freight;
    // if (Number(form.value.basic.tracking_price)) {
    updateTracking();
    // }
  } catch (e) {
    throw Error(e);
  }
};

const options = ref({});
Promise.all([
  getBaseOptions({ type: "purchase" }).then((res) => res.data),
  Promise.resolve({ test: [{ label: "没有数据", value: 1 }] }),
]).then((res) => {
  options.value = res.reduce((acc, cur) => ((acc = { ...acc, ...cur }), acc), {});
});

const total = computed(() => {
  return (form.value.sku || []).reduce(
    (acc, cur) => {
      acc.purchase_num += +cur.purchase_quantity;
      acc.tracking_price = toFixed(
        +acc.tracking_price + +(cur.tracking_price || 0) * +cur.purchase_quantity
      );
      return acc;
    },
    { purchase_num: 0, total_price: 0, tracking_price: 0, total_purchase_price: 0 }
  );
});

// 更新总运费
const trackingChange = async (row) => {
  calcUnitPurchasePrice(row);
  await 1;
  form.value.basic.tracking_price = total.value.tracking_price;
};
// 计算单个成本
const calcUnitPurchasePrice = (row) => {
  row.total_tracking_price = toFixed(row.tracking_price * row.purchase_quantity);
  form.value.sku = [...form.value.sku];
};
const toFixed = (val) => +XEUtils.toFixed(val, 2);

const updateTracking = async (row) => {
  const { basic, sku } = form.value;
  const { tracking_price } = basic;
  const price = tracking_price / sku.length;
  form.value.sku.forEach((d) => {
    d.tracking_price = Number((price / d.purchase_quantity).toFixed(6));
    calcUnitPurchasePrice(d);
  });
};

const changeSupplie = (val) => {
  const item = form.value.basic.supplier.find((i) => i.label == val);
  form.value.basic.purchase_type = item?.purchase_type;
};

const save = async () => {
  const formData = Object.assign({}, form.value);

  if (!formData.basic.purchase_type) {
    ElMessage.error("请选择供应商");
    return;
  }
  const is_tracking_price = formData.sku.every((i) => i.tracking_price >= 0);
  if (!is_tracking_price) {
    ElMessage.error("运费分摊不能为空");
    return;
  }
  const is_expect_delivery_time = formData.sku.every((i) => i.expect_delivery_time);
  if (!is_expect_delivery_time) {
    ElMessage.error("预计到货时间不能为空");
    return;
  }
  try {
    formData.basic.purchase_num = total.value.purchase_num;
    const res = await createPurchaseOrder(formData);
    ElMessage.success("操作成功");
    close();
  } catch (e) {
    throw Error(e);
  }
};

const close = () => {
  dialogVisible.value = false;
};

defineExpose({ open });
</script>
<style lang="scss">
.sampleTitle {
  position: relative;
  font-size: 16px;
  margin: 10px 6px 10px 0;
  padding-left: 8px;

  &::after {
    content: " ";
    height: 60%;
    width: 2px;
    position: absolute;
    left: 0;
    top: 20%;
    align-items: center;
    background-color: #3366f1;
  }
}
</style>
